﻿using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Sustainalytics.Claims;
using Ent = Sustainalytics.Entities;
using System.Web.Http.Cors;
using Sustainalytics.News.BusinessLogic;

namespace Sustainalytics.News.Service
{
    /// <summary>
    /// Notifications controller
    /// </summary>
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/v1/notifications")]
    public class NotificationsController : ApiController, INotificationsController
    {
        private static INotificationsManagement _notificationsManager { get; set; }

        /// <summary>
        /// Ctor
        /// </summary>
        public NotificationsController(INotificationsManagement notificationsManager, IClaimsChecker claimsChecker)
        {
            _notificationsManager = notificationsManager;
        }

        [Route("")]
        public HttpResponseMessage Get()
        {
            try
            {
                var notification = _notificationsManager.GetNotification();

                if (notification == null) return Request.CreateResponse(HttpStatusCode.NotFound);

                var notificationDto = new NotificationsDto();
                notificationDto.LoadFrom(notification);

                return Request.CreateResponse(HttpStatusCode.OK, notificationDto);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

        [Route("")]
        public HttpResponseMessage Post(NotificationsDto notification)
        {
            try
            {
                if (notification == null)
                    return Request.CreateResponse(HttpStatusCode.BadRequest, new {ErrorCode = ErrorCodes.NotificationErrorCodes.Notification_NotificationIsNull});

                var newNotification = new Ent.Notifications();
                notification.SaveTo(newNotification);

                var updateNotification = _notificationsManager.UpsertNotification(newNotification);

                notification.LoadFrom(updateNotification);

                return Request.CreateResponse(HttpStatusCode.OK, notification);
            }
            catch (NotificationNotValidException ex)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, new {ErrorCode = ErrorCodes.NotificationErrorCodes.Notification_NotificationNotValid});
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, System.Diagnostics.Debugger.IsAttached ? ex.Message : "Please contact the administrator, the error has been logged");
            }
        }
    }
}
